import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import http from '@/api/http';

const RegisterForm = ({onRegisterSuccess}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values) => {
    try {
      setLoading(true);
      const response = await http.post('/api/user/register', {
        username: values.username,
        password: values.password
      });
      if (response.code === 200) {
        message.success('注册成功');
        onRegisterSuccess(values.username)
        form.resetFields()
      } else {
        message.error(response.msg || '注册失败');
      }
    } catch (error) {
      message.error(error.msg || '注册失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      requiredMark={false}
      className="login-form"
    >
      <Form.Item
        label="用户名"
        name="username"
        rules={[
          { required: true, message: '请输入用户名' },
          { max: 20, message: '用户名不能超过20个字符' }
        ]}
      >
        <Input placeholder="请输入用户名" allowClear/>
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
        rules={[
          { required: true, message: '请输入密码' },
          { min: 6, message: '密码至少6个字符' }
        ]}
        hasFeedback
      >
        <Input.Password placeholder="请输入密码" allowClear/>
      </Form.Item>

      <Form.Item
        label="确认密码"
        name="confirm"
        dependencies={['password']}
        hasFeedback
        rules={[
          { required: true, message: '请确认密码' },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次输入的密码不一致'));
            },
          }),
        ]}
      >
        <Input.Password placeholder="请再次输入密码" allowClear />
      </Form.Item>
      <Button type="primary" block htmlType="submit" loading={loading}>
        注册
      </Button>
    </Form>
  );
};

export default RegisterForm;